<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <!-- <el-form-item label="学生名字" prop="stuname">
        <el-input
          v-model="queryParams.stuname"
          placeholder="请输入关联学生信息表"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item> -->
     
      <el-form-item label="学生名字" prop="stuname">
        <el-select v-model="queryParams.stuname" filterable allow-create remote :remote-method="remoteSearch"
          placeholder="请输入或选择学生信息" clearable @change="handleQuery" size="medium" class="w-full">
          <el-option v-for="item in studentList" :key="item.studentid" :label="item.stuname" :value="item.stuname" />
        </el-select>
      </el-form-item>
      <el-form-item label="服务人员" prop="userName">
        <el-select v-model="queryParams.userName" filterable allow-create remote :remote-method="remoteSearch"
          placeholder="请输入或选择服务人员" clearable @change="handleQuery" size="medium" class="w-full">
          <el-option v-for="item in serviceList" :key="item.userId || item.userName" :label="item.userName"
            :value="item.userName" />
        </el-select>
      </el-form-item>
      <el-form-item label="学生类型" prop="typename">
        <el-select v-model="queryParams.typename" filterable allow-create remote :remote-method="remoteSearch"
          placeholder="请输入或选择学生类型" clearable @change="handleQuery" size="medium" class="w-full">
          <el-option v-for="item in studenttypeList" :key="item.id || item.typename" :label="item.typename"
            :value="item.typename" />
        </el-select>
      </el-form-item>
      <el-form-item label="跟进类型" prop="processName">
        <el-select v-model="queryParams.processName" filterable allow-create remote :remote-method="remoteSearch"
          placeholder="请输入或选择跟进类型" clearable @change="handleQuery" size="medium" class="w-full">
          <el-option v-for="item in recordprogressList" :key="item.id || item.processName" :label="item.processName"
            :value="item.processName" />
        </el-select>
      </el-form-item>
<div>
  <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
</div>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['keyallocation:keyallocation:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['keyallocation:keyallocation:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['keyallocation:keyallocation:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['keyallocation:keyallocation:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="keyallocationList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="线索id" align="center" prop="allocationId" />
      <el-table-column label="学生" align="center" prop="stuname" />
      <el-table-column label="服务人员" align="center" prop="userName" />
      <el-table-column label="学生学校" align="center" prop="stuschool" />
      <el-table-column label="学生专业名" align="center" prop="stuspecialized" />
      <el-table-column label="学生班级" align="center" prop="stuclass" />
      <el-table-column label="学生类型" align="center" prop="typename" />
      <el-table-column label="跟进类型" align="center" prop="processName" />
      <el-table-column label="备注信息" align="center" prop="remarks" />
      <el-table-column label="状态" align="center" width="80">
        <template #default>
          <el-tag type="success">
            显示
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['keyallocation:keyallocation:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['keyallocation:keyallocation:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改线索分配对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="keyallocationRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="学生名字" prop="studentid">
          <el-select v-model="form.studentid" placeholder="请输入学生" clearable>
  <el-option v-for="item in studentList" :key="item.studentid" 
             :label="item.stuname" :value="item.studentid" />
</el-select>
        </el-form-item>
        <el-form-item label="服务人员" prop="userId">
          <el-select v-model="form.userId" placeholder="请选择服务人员" clearable>   
            <el-option v-for="item in serviceList" :key="item.userId" :label="item.userName" :value="item.userId" />
          </el-select>
        </el-form-item>
        <el-form-item label="备注信息" prop="remarks">
          <el-input v-model="form.remarks" placeholder="请输入关于此次分配的备注信息"/>
        </el-form-item>
        <!-- <el-form-item label="备注信息" prop="remarks">
  <div class="rich-text-container">
    <div id="remarkEditor" ref="remarkEditorRef"></div>
    <el-input v-model="form.remarks" type="hidden" />
  </div>
</el-form-item> -->
      </el-form>  
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Keyallocation">
import { listKeyallocation, getKeyallocation, delKeyallocation, addKeyallocation, updateKeyallocation } from "@/api/keyallocation/keyallocation"
import { listStudenttype } from "@/api/student/studenttype/studenttype"
import { listRecordprogress } from "@/api/student/recordprogress/recordprogress"
import { listService } from "@/api/system/user"
import {getStudentinfo,listStudentinfo}from "@/api/student/studentinfo/studentinfo"
import { reactive } from "vue"
import { ref } from "vue"
const { proxy } = getCurrentInstance()
const studenttypeList = ref([])
const recordprogressList = ref([])
const keyallocationList = ref([])
const serviceList = ref([])
const studentList=ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    studentid: null,
    userId: null,
    stuschool: null,
    stuspecialized: null,
    stuclass: null,
    stuTypeId: null,
    recordProgressId: null,
    remarks: null,
    state: null,
    studentid:null,
    stuname: null,
    userName: null,
    typename: null,
    processName: null
  },
  rules: {
  }
})

const { queryParams, form, rules } = toRefs(data)

/** 查询线索分配列表 */
function getList() {
  loading.value = true
  queryParams.value.state = 0
  console.log("queryParams", queryParams.value)
  listKeyallocation(queryParams.value).then(response => {
    keyallocationList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}
// 获取学生信息
const queryStudent=reactive({
  pageNum: 1,
  pageSize: 10,
  stuname: null,
  state: null
})
/** 获取学生列表 */
const getStudentList = () => {
  queryStudent.state = 0
  listStudentinfo(queryStudent).then(response => {
    studentList.value = response.rows
    console.log("学生列表", studentList.value)
  })
}
getStudentList()
/** 获取服务人员列表 */
const getServiceList = () => {
  listService().then(response => {
    serviceList.value = response.rows
    console.log("服务人员列表", serviceList.value)
  })
}
getServiceList()
const queryData=reactive({
  pageNum: 1,
    pageSize: 10,
    typename: null,
    state: null
})
/** 获取学生类型列表 */
const getStudenttypeList = () => {
  queryData.state = 0
  listStudenttype(queryData).then(response => {
    studenttypeList.value = response.rows
  })
}
getStudenttypeList()
const queryDas=reactive({
    pageNum: 1,
    pageSize: 10,
    processName: null,
    state: null
  })
/** 获取跟进进度列表 */
const getRecordprogressList = () => {
  queryDas.state = 0
  listRecordprogress(queryDas).then(response => {
    recordprogressList.value = response.rows
  })
}
getRecordprogressList()
// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    allocationId: null,
    createTime: null,
    studentid: null,
    userId: null,
    stuschool: null,
    stuspecialized: null,
    stuclass: null,
    stuTypeId: null,
    recordProgressId: null,
    remarks: null,
    state: null
  }
  proxy.resetForm("keyallocationRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  console.log("queryParams++++++", queryParams.value)
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.allocationId)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加线索分配"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _allocationId = row.allocationId || ids.value
  getKeyallocation(_allocationId).then(response => {
    form.value = response.data
    open.value = true
    title.value = "修改线索分配"
  })
}
/**
 * 根据学生ID查询学生信息并填充表单
 * @returns {Promise} 当表单填充完成后resolve
 */
 function searchStudent(studentid) {
  return new Promise((resolve, reject) => {
    getStudentinfo(studentid)
      .then(response => {
        console.log("+++", form.value);
        if (response.data) {
          console.log("学生信息", response.data);
          form.value.stuschool = response.data.stuschool;
          console.log("学生所在学校", form.value.stuschool);
          form.value.stuspecialized = response.data.stuspecialized;
          console.log("学生所在专业名", form.value.stuspecialized);
          console.log("学生所在班级", form.value.stuclass);
          form.value.stuTypeId = response.data.stuTypeId;
          console.log("学生类型", form.value.stuTypeId);
          form.value.recordProgressId = response.data.recordProgressId;
          console.log("跟进进度", form.value.recordProgressId);
          form.value.state = 0;
          resolve(true);
        } else {
          reject(new Error("未找到学生信息"));
        }
      })
      .catch(error => {
        console.error("获取学生信息失败", error);
        reject(error); // 将错误传递给调用者
      });
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["keyallocationRef"].validate(async valid => {
    if (valid) {
      if (form.value.allocationId != null) {
        updateKeyallocation(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        try {
          // 等待学生信息加载完成
          await searchStudent(form.value.studentid);
          console.log("学生信息已加载完成", form.value);
          // 确保学生信息已填充后再提交
          await addKeyallocation(form.value);
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        } catch (error) {
          console.error("提交失败", error);
          proxy.$modal.msgError(error.message || "提交失败，请重试");
        }
      }
    }
  });
}

function handleDelete(row) {
  let keyallocationIds = [];
  let confirmMessage = '';

  if (row && row.allocationId) {
    keyallocationIds = [row.allocationId];
    confirmMessage = `是否确认删除学生"${row.stuname}"的记录？`;
  } else if (ids.value.length > 0) {
    keyallocationIds = ids.value;
    const selectedCount = ids.value.length;
    confirmMessage = `是否确认删除选中的${selectedCount}条学生记录？`;
  } else {
    proxy.$modal.msgWarning("请选择要删除的记录");
    return;
  }

  proxy.$modal.confirm(confirmMessage).then(async () => {
    try {
      loading.value = true;
      await Promise.all(keyallocationIds.map(id => {
        console.log("删除线索分配", id);
        return updateKeyallocation({
          allocationId: id,
          state: 1
        });
      }));
      keyallocationList.value = keyallocationList.value.filter(
        item => !keyallocationIds.includes(item.allocationId)
      );

      proxy.$modal.msgSuccess("删除成功");
    } catch (error) {
      // 关键：打印错误信息，定位问题
      console.error("删除失败:", error);
      proxy.$modal.msgError("删除失败: " + (error.message || "未知错误"));
    } finally {
      loading.value = false;
      ids.value = [];
      single.value = true;
      multiple.value = true;
    }
  }).catch(() => { });
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('keyallocation/keyallocation/export', {
    ...queryParams.value
  }, `keyallocation_${new Date().getTime()}.xlsx`)
}

getList()
</script>
